package com.tianzj.mvc.system.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tianzj.mvc.system.dao.SysUserRoleMapper;
import com.tianzj.mvc.system.pojo.SysUserRole;
import com.tianzj.mvc.system.pojo.SysUserRoleExample;
import com.tianzj.mvc.system.service.SysUserRoleService;
import com.tianzj.util.SnowflakeIdWorker;

@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {

	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;
	
	public SysUserRoleExample getExample(SysUserRole sysUserRole){
		SysUserRoleExample sysUserRoleExample =new SysUserRoleExample();
		SysUserRoleExample.Criteria criteria = sysUserRoleExample.createCriteria();
		if(sysUserRole.getUserId()!=null){
			criteria.andUserIdEqualTo(sysUserRole.getUserId());
		}
		if(sysUserRole.getRoleId()!=null){
			criteria.andRoleIdEqualTo(sysUserRole.getRoleId());
		}
		if(sysUserRole.getStatus()!=null){
			criteria.andStatusEqualTo(sysUserRole.getStatus());
		}else{
			criteria.andStatusEqualTo(1L);
		}
		return sysUserRoleExample;
	}
	@Override
	public void deleteByUserId(Long userId) {
		SysUserRole sysUserRole =new SysUserRole();
		List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectByExample(getExample(sysUserRole));
		for (SysUserRole userRole : sysUserRoles) {
			sysUserRoleMapper.deleteByPrimaryKey(userRole.getId());
		}
	}

	@Override
	public void addUserRole(Long userId, String roleIds) {
		String[] roleIdArray = roleIds.split(",");
		for (String roleId : roleIdArray) {
			SysUserRole sysUserRole =new SysUserRole();
			sysUserRole.setRoleId(Long.parseLong(roleId));
			sysUserRole.setUserId(userId);
			sysUserRole.setStatus(1L);
			sysUserRole.setId(new SnowflakeIdWorker(0, 0).nextId());
			sysUserRoleMapper.insertSelective(sysUserRole);
		}
	}

	@Override
	public List<Long> getRoleIdByUserId(Long userId) {
		return sysUserRoleMapper.getRoleIdByUserId(userId);
	}

	@Override
	public boolean getUserRoleByRoleIds(String roleId) {
		boolean flag=true;
		SysUserRole sysUserRole =new SysUserRole();
		sysUserRole.setRoleId(Long.parseLong(roleId));
		List<SysUserRole> sysUserRoles =sysUserRoleMapper.selectByExample(getExample(sysUserRole));
		if(sysUserRoles!=null&&sysUserRoles.size()!=0){
			flag=false;
		}
		return flag;
	}
	@Override
	public List<SysUserRole> getUserRoleByUserId(Long userId) {
		SysUserRole sysUserRole = new SysUserRole();
		sysUserRole.setUserId(userId);
		return sysUserRoleMapper.selectByExample(getExample(sysUserRole));
	}

}
